<?php

namespace app\index\controller;

use think\Cache;
use think\Controller;
use think\Db;
use think\Exception;
use think\Loader;
use think\Request;
use think\Validate;

header('Access-Control-Allow-Origin: *');                             // 允许所有来源访问，或者可以指定特定来源，比如 'http://www.fast.com'
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE');       // 允许的方法
header('Access-Control-Allow-Headers: Content-Type, Authorization');  // 允许的请求头

class Api extends Controller
{
    /**
     * fa_user表son_ids字段写入
     * */
    public function updateSonIds()
    {
        /*$list = Db::table('fa_user')->select();
        foreach ($list as $k => $v) {
            $user_list = [];
            getAllSon($v['id'], $user_list);

            // 一维数组从小到大排序
            sort($user_list);
            $son_ids = implode(',', $user_list);
            Db::table('fa_user')->where('id', $v['id'])->update(['son_ids' => $son_ids, 'team_count' => count($user_list)]);
        }*/
    }

    /**
     * 短信发送
     * */
    public function sendSms()
    {
        $input = Request()->param();

        $mobile = $input['mobile'];

        if (empty($mobile)) return apiReturn(2, '请输入手机号码');

        //获取手机号
        $pattern = "/^1[0123456789]\d{9}$/";
        if (empty($mobile)) {
            return apiReturn(2, '请输入手机号');
        } else {
            if (preg_match($pattern, $mobile)) {
                //判断当前手机有没有发送过验证码
                $result = Db::name('mini_sms_code')->where(['mobile' => $mobile])->order('create_time desc')->find();
                $result = time() - $result['create_time'];
                if ($result < 60 and $result > 0) {
                    return apiReturn(2, '当前手机号操作频繁,请稍后再试');
                }
                $authnum = rand(100000, 999999);
                $statusStr = [
                    "0" => 1,
                    "-1" => "参数不全",
                    "-2" => "服务器空间不支持,请确认支持curl或者fsocket，联系您的空间商解决或者更换空间！",
                    "30" => "密码错误",
                    "40" => "账号不存在",
                    "41" => "余额不足",
                    "42" => "帐户已过期",
                    "43" => "IP地址限制",
                    "50" => "内容含有敏感词"
                ];
                $smsapi = "http://api.smsbao.com/";
                $user = 'xvzhou';         //短信平台帐号
                $pass = md5('8691xzadz'); //短信平台密码
                $content = '【特汇鲜品】您的验证码是' . $authnum . '。如非本人操作，请忽略本短信';
                $phone = $mobile;//要发送短信的手机号码
                $sendurl = $smsapi . "sms?u=" . $user . "&p=" . $pass . "&m=" . $phone . "&c=" . urlencode($content);
                $result = file_get_contents($sendurl);
                if ($result == 0) {
                    $info['code'] = $authnum;
                    $info['mobile'] = $phone;
                    $info['create_time'] = time();
                    $info['failure_time'] = time() + 600;//失效时间：10分钟
                    Db::name('mini_sms_code')->insert($info);
                    return apiReturn(1, '短信发送成功');
                } else {
                    return apiReturn(2, $statusStr[$result]);
                }
            } else {
                return apiReturn(2, '手机号码格式错误');
            }
        }
    }

    /**
     * 注册
     * */
    public function register()
    {
        $input = Request()->param();

        $mobile = $input['mobile'];
        $code = $input['code'];
        $share_code = $input['share_code'];
        $password = $input['password'];

        if (empty($mobile)) apiReturn(2, '请输入手机号');
        if (!isValidPhoneNumber($mobile)) apiReturn(2, '手机号格式错误');
        if (empty($code)) apiReturn(2, '请输入验证码');
        if (empty($share_code)) apiReturn(2, '请输入邀请码');
        if (empty($password)) apiReturn(2, '请输入密码');
        if (strlen($password) < 6) apiReturn(2, '密码长度至少6位');

        $sms_code = Db::table('fa_sms')->where('mobile', $mobile)->where('event', 'register')->order('id desc')->find();

        if (empty($sms_code) || $sms_code['code'] != $code) apiReturn(2, '验证码错误');
        if ($sms_code['times'] > 0) apiReturn(2, '验证码已失效');

        $find = Db::table('fa_user')->where('mobile', $mobile)->find();
        if ($find) apiReturn(2, '手机号已注册');

        // 查询邀请码用户是否是达人
        $info = Db::table('fa_user')->field('id,user_type,parent_ids')->where('unique_id', $share_code)->find();
        if (empty($info)) apiReturn(2, '邀请码不存在');
        if ($info['user_type'] != 2) apiReturn(2, '邀请码用户非VIP');

        Loader::import('random.Random', EXTEND_PATH);
        $obj = new \Random();
        $salt = $obj::alnum();

        $time = time();

        $uqi = 0;
        do {
            if ($uqi > 5) {
                $NewUniqueId = rand(10000000, 39999999);
            } else {
                $NewUniqueId = rand(40000000, 99999999);
            }
            $countUnique = Db::table("fa_user")->field('id')->where(['unique_id' => $NewUniqueId])->count();
            if ($uqi > 10) {
                apiReturn(2, '生成邀请码失败');
            }
            $uqi++;
        } while ($countUnique);

        Db::startTrans();
        try {
            $data = [
                'mobile' => $mobile,
                'password' => getEncryptPassword($password, $salt),
                'salt' => $salt,
                'avatar' => '/assets/img/avatar.png',
                'loginip' => getRealIp(),
                'joinip' => getRealIp(),
                'jointime' => $time,
                'createtime' => $time,
                'updatetime' => $time,
                'prevtime' => $time,
                'logintime' => $time,
                'status' => 'normal',
                'unique_id' => $NewUniqueId,
                'parent_user_id' => $info['id'],
                'parent_ids' => $info['parent_ids'] . $info['id'] . ',',
            ];
            $user_id = Db::table('fa_user')->insertGetId($data);

            Db::table('fa_sms')->where('id', $sms_code['id'])->setInc('times');

            Db::commit();
            apiReturn(1, '注册成功');
        } catch (Exception $e) {
            Db::rollback();
            apiReturn(2, '注册失败');
        }
    }

    /**
     * 短信验证码修改密码
     * */
    public function smsCodeResetPassword()
    {
        $input = Request()->param();

        $mobile = $input['mobile'];
        $password = $input['password'];
        $code = $input['code'];

        if (empty($mobile)) apiReturn(2, '请输入手机号');
        if (!isValidPhoneNumber($mobile)) apiReturn(2, '手机号格式错误');
        if (empty($code)) apiReturn(2, '请输入验证码');
        if (empty($password)) apiReturn(2, '请输入密码');
        if (strlen($password) < 6) apiReturn(2, '密码长度至少6位');

        $sms_code = Db::table('fa_sms')->where('mobile', $mobile)->where('event', 'changepwd')->order('id desc')->find();

        if (empty($sms_code) || $sms_code['code'] != $code) apiReturn(2, '验证码错误');
        if ($sms_code['times'] > 0) apiReturn(2, '验证码已失效');

        $find = Db::table('fa_user')->where('mobile', $mobile)->find();
        if (empty($find)) apiReturn(2, '手机号不存在');

        Db::startTrans();
        try {
            Db::table('fa_user')->where('mobile', $mobile)->setField('password', getEncryptPassword($password, $find['salt']));
            Db::table('fa_sms')->where('id', $sms_code['id'])->setInc('times');

            Db::commit();
            apiReturn(1, '修改密码成功');
        } catch (Exception $e) {
            Db::rollback();
            apiReturn(2, '修改密码失败');
        }
    }

    /**
     * 原密码修改密码
     * */
    public function resetPassword()
    {
        $input = Request()->param();

        $user_id = $input['user_id'];
        $old_password = $input['old_password'];
        $new_password = $input['new_password'];

        if (empty($user_id)) apiReturn(3, '您还未登录，请先登录');
        if (empty($old_password)) apiReturn(2, '请输入原密码');
        if (empty($new_password)) apiReturn(2, '请输入新密码');
        if (strlen($old_password) < 6 || strlen($new_password) < 6) apiReturn(2, '密码长度至少6位');

        $info = Db::table('fa_user')->where('id', $user_id)->find();
        if (empty($info)) apiReturn(3, '用户不存在');

        if ($info['password'] != getEncryptPassword($old_password, $info['salt'])) apiReturn(2, '原密码错误');

        $data = [
            'password' => getEncryptPassword($new_password, $info['salt']),
            'updatetime' => time()
        ];

        $res = Db::table('fa_user')->where('id', $user_id)->update($data);
        if ($res) {
            apiReturn(1, '修改密码成功');
        } else {
            apiReturn(2, '修改密码失败');
        }
    }

    /**
     * 设置支付密码
     * */
    public function setPayPassword()
    {
        $input = Request()->param();

        $user_id = $input['user_id'];
        $pay_pwd = $input['pay_pwd'];
        $new_pay_pwd = $input['new_pay_pwd'] ? : '';

        if (empty($user_id)) apiReturn(3, '您还未登录，请先登录');
        if (empty($pay_pwd)) apiReturn(2, '请输入支付密码');

        $info = Db::table('fa_user')->where('id', $user_id)->find();
        if ($info) {
            if ($info['pay_pwd'] == '') {
                // 初次设置密码
                $new_pwd = getEncryptPassword($pay_pwd, $info['salt']);
            } else {
                if (empty($new_pay_pwd)) apiReturn(2, '请输入新密码');
                if ($info['pay_pwd'] != getEncryptPassword($pay_pwd, $info['salt'])) apiReturn(2, '原密码错误');
                $new_pwd = getEncryptPassword($new_pay_pwd, $info['salt']);
            }

            $data = [
                'pay_pwd' => $new_pwd,
                'updatetime' => time()
            ];
            $res = Db::table('fa_user')->where('id', $user_id)->update($data);
            if ($res) {
                apiReturn(1, '修改密码成功');
            } else {
                apiReturn(2, '修改密码失败');
            }
        } else {
            apiReturn(3, '账号不存在');
        }
    }

    /**
     * 手机号密码登录
     * */
    public function passwordLogin()
    {
        $input = Request()->param();

        $mobile = $input['mobile'];
        $password = $input['password'];

        if (empty($mobile)) apiReturn(2, '请输入手机号');
        if (empty($password)) apiReturn(2, '请输入密码');

        $info = Db::table('fa_user')->where(['mobile' => $mobile])->find();
        if (empty($info)) apiReturn(2, '手机号未注册');

        if ($info['status'] == 'hidden') apiReturn(3, '您的账号已被禁用');

        if ($info['password'] != getEncryptPassword($password, $info['salt'])) apiReturn(2, '密码错误');

        apiReturn(1, '登录成功', $info['id']);
    }

    /**
     * 手机号验证码登录
     * */
    public function smsLogin()
    {
        $input = Request()->param();

        $mobile = $input['mobile'];
        $code = $input['code'];

        if (empty($mobile)) apiReturn(2, '请输入手机号');
        if (empty($code)) apiReturn(2, '请输入验证码');

        $info = Db::table('fa_user')->where(['mobile' => $mobile])->find();
        if (empty($info)) apiReturn(4, '手机号未注册');
        if ($info['status'] == 'hidden') apiReturn(3, '您的账号已被禁用');

        $sms_code = Db::table('fa_sms')->where('mobile', $mobile)->where('event', 'login')->order('id desc')->find();

        if (empty($sms_code) || $sms_code['code'] != $code) apiReturn(2, '验证码错误');
        if ($sms_code['times'] > 0) apiReturn(2, '验证码已失效');

        apiReturn(1, '登录成功', $info['id']);
    }

    public function getOpenid()
    {
        $input = Request()->param();

        $code = $input['code'];

        if (empty($code)) apiReturn(2, '系统繁忙，请稍后再试~');

        $appid = C('XCX_APPID');
        $secret = C('XCX_SECRET');
        $grant_type = 'authorization_code';
        $url = 'https://api.weixin.qq.com/sns/jscode2session?';

        $param = [
            'appid' => $appid,
            'secret' => $secret,
            'js_code' => $code,
            'grant_type' => $grant_type
        ];
        $param_str = http_build_query($param);
        $url .= $param_str;

        $user_data = json_decode(file_get_contents($url));

        if ($user_data->errcode) apiReturn(2, '系统繁忙，请稍后再试~');

        $openid = $user_data->openid;
        if ($openid) $user_id = Db::table('fa_user')->where('openid', $openid)->value('id');

        $data = [
            'openid' => $openid,
            'user_id' => $user_id ? : 0
        ];

        apiReturn(1, '获取数据成功', $data);
    }

    /**
     * 省市区地址获取
     * */
    public function getRegion()
    {
        $province_list = Db::name('mini_province')->field('province_id value,name label')->order('province_id asc')->select();
        foreach ($province_list as &$v) {
            $city_list = Db::name('mini_city')->field('city_id value,name label')->where(['province_id' => $v['value']])->order('city_id asc')->select();

            foreach ($city_list as &$val) {
                $area_list = Db::name('mini_area')->field('area_id value,name label')->where(['city_id' => $val['value']])->order('area_id asc')->select();
                $val['children'] = $area_list;
            }

            $v['children'] = $city_list;
        }

        apiReturn(1, '获取数据成功', $province_list);
    }

    /**
     * 首页banner
     * */
    public function indexBanner()
    {
        $banner_list = Db::name('mini_banner')->field('id,img')->order('id desc')->select();

        if ($banner_list) {
            foreach ($banner_list as &$v) {
                $v['img'] = getPicture($v['img']);
            }
            apiReturn(1, '获取数据成功', $banner_list);
        } else {
            apiReturn(2, '暂无更多数据', []);
        }
    }

    /**
     * 文章详情
     * */
    public function articleDetail()
    {
        $input = Request()->param();

        $id = $input['id'];

        if (empty($id)) apiReturn(2, '文章ID缺失');

        $info = Db::name('mini_article')->field('id,title,content')->where(['id' => $id])->find();
        if ($info) {
            $info['content'] = doEditorContent($info['content']);

            apiReturn(1, '获取数据成功', $info);
        } else {
            apiReturn(2, '文章不存在或已删除');
        }
    }

    /**
     * 首页福利专区 推荐/热门 商品
     * */
    public function indexGoodsList()
    {
        $input = Request()->param();

        $type = $input['type'] ? : 1;// 1：推荐，2：热门

        $where['upper'] = 1;
        $where['one_type_id'] = 2;
        if ($type == 1) {
            $where['is_recommend'] = 1;
        } else {
            $where['is_hot'] = 1;
        }

        $list = Db::name('mini_goods')->field('id,name,one_type_id,min_price,min_use_coupon_price,img')->where($where)->order('id desc')->limit(4)->select();
        if ($list) {
            $list = addOtherTableDataToList($list, 'img', Db::name('mini_picture'), 'img_path', 'path', 'id');
            foreach ($list as &$v) {
                $v['img'] = doImgPath($v['img_path']);
                $v['price_info'] = doPrice($v['min_price']);
                $v['min_use_coupon_price'] = intval($v['min_use_coupon_price']);
            }
        }

        apiReturn(1, '获取数据成功', $list);
    }

    /**
     * 商品分类
     * */
    public function goodsTypeList()
    {
        $list = Db::name('mini_goods_type')->field('id,name,img')->order('id asc')->select();
        if ($list) {
            foreach ($list as &$v) {
                $v['img'] = getPicture($v['img']);
            }
            apiReturn(1, '获取数据成功', $list);
        } else {
            apiReturn(2, '暂无更多数据', []);
        }
    }

    /**
     * 商品列表
     * */
    public function goodsList()
    {
        $input = Request()->param();

        $name = $input['name'];
        $one_type_id = $input['one_type_id'] ? : 0;
        $is_recommend = $input['is_recommend'] ? : 0;
        $sort = $input['sort'] ? : 0;//1：综合排序，2：销量排序，3：价格排序
        $page = $input['page'] ? : 1;
        $pagesize = $input['pagesize'] ? : 10;

        $where['upper'] = 1;

        if ($name) $where['name'] = ['LIKE', '%' . $name . '%'];
        if ($is_recommend) $where['is_recommend'] = $is_recommend;
        if ($one_type_id) $where['one_type_id'] = $one_type_id;

        if ($sort == 2) {
            $order = 'sales_count desc';
        } else if ($sort == 3) {
            $order = 'min_price asc';
        } else {
            $order = 'create_time desc';
        }

        $list = Db::name('mini_goods')->field('id,name,one_type_id,min_price,min_use_coupon_price,img')->where($where)->order($order)->page($page, $pagesize)->select();
        if ($list) {
            $list = addOtherTableDataToList($list, 'img', Db::name('mini_picture'), 'img_path', 'path', 'id');
            foreach ($list as &$v) {
                $v['img'] = doImgPath($v['img_path']);
                $v['price_info'] = doPrice($v['min_price']);
                $v['min_use_coupon_price'] = intval($v['min_use_coupon_price']);
            }
            apiReturn(1, '获取数据成功', $list);
        } else {
            apiReturn(2, '暂无更多数据', []);
        }
    }

    /**
     * 商品详情
     * */
    public function goodsDetail()
    {
        $input = Request()->param();

        $id = $input['id'];

        if (empty($id)) apiReturn(2, '商品ID缺失');

        $info = Db::name('mini_goods')->field('id,name,one_type_id,img,imgs,sales_count,min_price,content')->where(['id' => $id])->find();
        if ($info) {
            $info['img'] = getPicture($info['img']);
            $info['imgs'] = doImgs($info['imgs']);
            $info['content'] = doEditorContent($info['content']);

            $sku_data = getSku($id);

            $info['sku_list'] = $sku_data['sku_list'];
            $info['sku_value_list'] = $sku_data['sku_value_list'];

            $comment_count = Db::name('mini_goods_comment')->where(['goods_id' => $id])->count();
            $info['comment_count'] = $comment_count;

            $info['price_info'] = doPrice($info['min_price']);

            //评价列表
            $comment_list = Db::name('mini_goods_comment c')
                ->join('fa_user u', 'c.user_id = u.id', 'left')
                ->field('c.id,u.avatar,u.nickname,c.star,c.content,c.imgs,c.create_time')
                ->where(['c.goods_id' => $id])
                ->order('c.create_time desc')
                ->limit(2)
                ->select();
            if ($comment_list) {
                foreach ($comment_list as &$v) {
                    $v['avatar'] = doImgPath($v['avatar']);
                    $v['imgs'] = doImgs($v['imgs']);
                    $v['star'] = intval($v['star']);
                    $v['create_time'] = timeFormat($v['create_time'], 'Y-m-d');
                }
            } else {
                $comment_list = [];
            }
            $info['comment_list'] = $comment_list;

            apiReturn(1, '获取数据成功', $info);
        } else {
            apiReturn(2, '商品不存在或已删除');
        }
    }

    /**
     * 商品评价列表
     * */
    public function goodsCommentList()
    {
        $input = Request()->param();

        $id = $input['id'];
        $page = $input['page'] ? : 1;
        $pagesize = $input['pagesize'] ? : 10;

        if (empty($id)) apiReturn(2, '商品ID缺失');

        $list = Db::name('mini_goods_comment c')
            ->join('fa_user u', 'c.user_id = u.id', 'left')
            ->field('c.id,u.avatar,u.nickname,c.star,c.content,c.imgs,c.create_time')
            ->where(['c.goods_id' => $id])
            ->order('c.create_time desc')
            ->page($page, $pagesize)
            ->select();
        if ($list) {
            foreach ($list as &$v) {
                $v['avatar'] = doImgPath($v['avatar']);
                $v['imgs'] = doImgs($v['imgs']);
                $v['star'] = intval($v['star']);
                $v['create_time'] = timeFormat($v['create_time'], 'Y-m-d');
            }

            apiReturn(1, '获取数据成功', $list);
        } else {
            apiReturn(2, '暂无更多数据', []);
        }
    }

    /**
     * 购物车商品数量校正
     * tips：在小程序 onHide 和 onUnload 中调用该接口
     * */
    public function doCarGoodsCount()
    {
        $input = Request()->param();

        $car_list = json_decode($input['car_list'], true);//[{"id":"4","count":"8"}]

        if ($car_list) {
            foreach ($car_list as &$v) {
                Db::name('mini_goods_car')->where(['id' => $v['id']])->setField('count', $v['count']);
            }
        }
    }

    /**
     * 加入购物车
     * */
    public function addGoodsCar()
    {
        $input = Request()->param();

        $id = $input['id'];//商品id
        $user_id = $input['user_id'];
        if (checkUserStatus($user_id) === false) apiReturn(3, '您的账号已被禁用，请联系后台工作人员');
        $sku_id = $input['sku_id'];//属性id组合；sku_value表sku_id
        $count = $input['count'];

        if (empty($id)) apiReturn(2, '商品ID缺失');
        if (empty($user_id)) apiReturn(3, '您还未登录，请先登录');
        if (empty($sku_id)) apiReturn(2, '属性ID缺失');
        if ($count <= 0) apiReturn(2, '商品数量异常');

        $goods_info = Db::name('mini_goods')->where(['id' => $id])->find();
        if ($goods_info) {
            $goods_car_count = Db::name('mini_goods_car')->where(['user_id' => $user_id, 'goods_id' => $id])->value('count');

            $sku_info = Db::name('mini_sku_value')->field('sku_id,img,price')->where(['sku_id' => $sku_id, 'goods_id' => $id])->find();
            if ($sku_info) {
                $car_info = Db::name('mini_goods_car')->where(['user_id' => $user_id, 'goods_id' => $id, 'sku_id' => $sku_id])->find();
                if ($car_info) {
                    //该商品之前已经加入过购物车，这个时候只需要增加购物车数量即可
                    $res = Db::name('mini_goods_car')->where(['id' => $car_info['id']])->setInc('count', $count);
                } else {
                    //该商品第一次加入购物车，添加购物车数据
                    $data = [
                        'user_id' => $user_id,
                        'goods_id' => $id,
                        'img' => $sku_info['img'],
                        'sku_id' => $sku_info['sku_id'],
                        'count' => $count,
                        'price' => $sku_info['price'],
                        'create_time' => time()
                    ];
                    $res = Db::name('mini_goods_car')->insert($data);
                }
            } else {
                apiReturn(2, '属性不存在或已删除');
            }

            if ($res) {
                $count = Db::name('mini_goods_car')->where(['user_id' => $user_id])->count();

                apiReturn(1, '添加成功', $count ? : 0);
            } else {
                apiReturn(2, '添加购物车失败');
            }
        } else {
            apiReturn(2, '商品不存在或已删除');
        }
    }

    public function goodsCarCount()
    {
        $input = Request()->param();

        $user_id = $input['user_id'];

        if (checkUserStatus($user_id) === false) apiReturn(3, '您的账号已被禁用');
        if (empty($user_id)) apiReturn(3, '您还未登录，请先登录');

        $count = Db::name('mini_goods_car')->where(['user_id' => $user_id])->count();

        apiReturn(1, '获取数据成功', $count ? : 0);
    }

    /**
     * 购物车列表
     * */
    public function goodsCarList()
    {
        $input = Request()->param();

        $user_id = $input['user_id'];
        if (checkUserStatus($user_id) === false) apiReturn(3, '您的账号已被禁用，请联系后台工作人员');

        if (empty($user_id)) apiReturn(3, '您还未登录，请先登录');

        $list = Db::name('mini_goods_car')->where(['user_id' => $user_id])->order('id desc')->select();
        if ($list) {
            foreach ($list as &$v) {
                $v['img'] = $v['img'] ? getPicture($v['img']) : getGoodsImg($v['goods_id']);
                $goods_info = Db::name('mini_goods')->where(['id' => $v['goods_id']])->find();
                $v['goods_name'] = $goods_info['name'];
                $v['active'] = false;

                // 获取商品的价格
                $price = Db::name('mini_sku_value')->where(['sku_id' => $v['sku_id']])->value('price');
                $v['price'] = $price ? : $v['price'];

                if ($sku_list = getSkuName(explode('-', $v['sku_id']))) $v['sku'] = implode('，', array_column($sku_list, 'name'));
            }

            apiReturn(1, '获取数据成功', $list);
        } else {
            apiReturn(2, '暂无数据');
        }
    }

    /**
     * 移除购物车商品
     * */
    public function removeGoodsCar()
    {
        $input = Request()->param();
        $car_ids = $input['car_ids'];
        if (empty($car_ids)) apiReturn(2, '购物车ID缺失');
        $res = Db::name('mini_goods_car')->where(['id' => ['IN', $car_ids]])->delete();
        if ($res) {
            apiReturn(1, '移除成功');
        } else {
            apiReturn(2, '移除失败');
        }
    }

    /**
     * 购物车订单确认页
     * */
    public function goodsCarOrderConfirm()
    {
        $input = Request()->param();

        $user_id = $input['user_id'];
        if (checkUserStatus($user_id) === false) apiReturn(3, '您的账号已被禁用');
        $car_ids = $input['car_ids'];

        if (empty($user_id)) apiReturn(3, '您还未登录，请先登录');
        if (empty($car_ids)) apiReturn(2, '购物车ID缺失');

        // 用户信息
        $user_info = Db::table('fa_user')->field('id,nickname,mobile')->where(['id' => $user_id])->find();
        if (empty($user_info)) apiReturn(2, '用户信息不存在或已删除');

        $car_list = Db::name('mini_goods_car')->field('id,goods_id,img,sku_id,price,count')->where(['id' => ['IN', $car_ids]])->order('id desc')->select();
        $all_price = 0;
        $all_use_coupon_price = 0;
        if ($car_list) {
            foreach ($car_list as &$v) {
                $goods_info = Db::name('mini_goods')->field('name')->where(['id' => $v['goods_id']])->find();

                $v['goods_name'] = $goods_info['name'];
                $v['img'] = $v['img'] ? getPicture($v['img']) : getGoodsImg($v['goods_id']);
                $v['sku'] = implode('，', array_column(getSkuName(explode('-', $v['sku_id'])), 'name'));

                // 获取商品的价格
                $sku_info = Db::name('mini_sku_value')->field('price,use_coupon_price')->where(['sku_id' => $v['sku_id']])->find();
                $v['price'] = $sku_info['price'] ? : $v['price'];

                $all_price += sprintf("%.2f", $sku_info['price'] * $v['count']);

                $all_use_coupon_price += sprintf("%.2f", $sku_info['use_coupon_price'] * $v['count']);
            }

            //默认收货地址
            $default_address = Db::name('mini_address')->field('id,username,mobile,title,detail_address')->where(['user_id' => $user_id])->order('is_default desc,id desc')->find();
            $default_address['address'] = $default_address['title'] . $default_address['detail_address'];


            $data = [
                'goods_list' => $car_list,
                'all_price' => sprintf('%.2f', $all_price),
                'all_use_coupon_price' => sprintf('%.2f', $all_use_coupon_price),
                'address' => $default_address ? : [],
                'user_info' => $user_info,
            ];
            apiReturn(1, '获取数据成功', $data);
        } else {
            apiReturn(2, '购物车商品数据异常');
        }
    }

    /**
     * 购物车立即支付【生成待支付订单】 之后 发起支付
     * */
    public function addGoodsCarOrder()
    {
        $input = Request()->param();

        $user_id = $input['user_id'];
        if (checkUserStatus($user_id) === false) apiReturn(3, '您的账号已被禁用');
        $car_ids = $input['car_ids'];
        $address_id = $input['address_id'];
        $use_coupon = $input['use_coupon'];
        $all_price = $input['all_price'];
        $pay_price = $input['pay_price'];
        $pay_type = $input['pay_type'];
        $remark = $input['remark'];
        $from = $input['from'] ? : 2;// H5端该参数传1，小程序默认可以不传

        if (empty($user_id)) apiReturn(3, '您还未登录，请先登录');
        if (empty($car_ids)) apiReturn(2, '购物车ID缺失');
        if ($pay_price <= 0) apiReturn(2, '商品金额错误');

        $user_info = Db::table('fa_user')->where(['id' => $user_id])->find();
        if (empty($user_info)) apiReturn(2, '用户信息不存在或已删除');

        if (empty($address_id)) apiReturn(2, '请选择收货地址');

        if ($pay_type == 2) {
            // 使用余额支付，判断账户余额是否充足
            $money = Db::table('fa_user')->where(['id' => $user_id])->value('money');
            if ($money < $pay_price) apiReturn(2, '账户余额不足');
        }

        $time = time();

        Db::startTrans();
        try {
            $car_list = Db::name('mini_goods_car')->field('id,goods_id,price,sku_id,count')->where(['id' => ['IN', $car_ids]])->select();

            if ($car_list) {
                if ($use_coupon == 1) {
                    $use_coupon_count = Db::name('mini_goods_car')->where(['id' => ['IN', $car_ids]])->sum('count');

                    if ($user_info['coupon_count'] < $use_coupon_count) apiReturn(2, '您的抵扣券数量不足');
                }

                //支付订单号
                $order_sn = createOrderSn();

                $order_data = [
                    'user_id' => $user_id,
                    'order_sn' => $order_sn,
                    'pay_order_sn' => $order_sn,
                    'all_price' => $all_price,
                    'pay_price' => $pay_price,
                    'pay_type' => $pay_type,
                    'use_coupon_count' => $use_coupon_count,
                    'remark' => $remark,
                    'car_ids' => $car_ids,
                    'from' => $from,
                    'create_time' => $time
                ];

                $address_info = Db::name('mini_address')->where(['id' => $address_id])->find();
                $order_data['get_username'] = $address_info['username'];
                $order_data['get_mobile'] = $address_info['mobile'];
                $order_data['get_sex'] = $address_info['sex'];
                $order_data['get_address'] = $address_info['title'] . $address_info['detail_address'];
                $order_data['get_lat'] = $address_info['lat'];
                $order_data['get_lng'] = $address_info['lng'];

                $order_id = Db::name('mini_order')->insertGetId($order_data);

                $goods_order = [];
                foreach ($car_list as &$v) {
                    $goods_info = Db::name('mini_goods')->field('id,name,img')->where(['id' => $v['goods_id']])->find();

                    $sku_info = Db::name('mini_sku_value')->where(['goods_id' => $v['goods_id'], 'sku_id' => $v['sku_id']])->find();
                    if (!$sku_info) apiReturn(2, $goods_info['name'] . '属性不存在或已删除');

                    //准备订单副表数据
                    $goods_info = Db::name('mini_goods')->field('id,name')->where(['id' => $v['goods_id']])->find();
                    $sku_info = Db::name('mini_sku_value')->where(['goods_id' => $v['goods_id'], 'sku_id' => $v['sku_id']])->find();

                    $goods_order[] = [
                        'order_id' => $order_id,
                        'goods_id' => $v['goods_id'],
                        'sku_id' => $sku_info['sku_id'],
                        'img' => $sku_info['img'] ? : $goods_info['img'],
                        'name' => $goods_info['name'],
                        'price' => $sku_info['price'],
                        'use_coupon_price' => $sku_info['use_coupon_price'],
                        'count' => $v['count'],
                        'use_coupon' => $use_coupon,
                        'create_time' => $time
                    ];
                }

                $vice_order_res = Db::name('mini_vice_order')->insertAll($goods_order);
                if ($vice_order_res) {
                    // 清除对应购物车商品
                    Db::name('mini_goods_car')->where(['id' => ['IN', $car_ids]])->delete();

                    if ($pay_type == 1) {
                        //微信支付
                        Loader::import('wxsdk\wxPay', EXTEND_PATH);
                        $obj = new \wxPay();
                        //调用示例（最后两个参数为可选参数）
                        $pay_price = C('TEST_PAY') ? 0.01 : $pay_price;
                        $pay_data = $obj->jsApi($user_info['openid'], $pay_price, $order_sn, '商品支付', getHost() . '/index/Notify/notice', '', 1);

                        $return_data = [
                            'pay_data' => $pay_data,
                            'order_sn' => $order_sn
                        ];
                    } else {
                        // 使用余额支付
                        action('Index/Notify/doGoodsOrder', $order_sn);
                    }

                    Db::commit();
                    apiReturn(1, '获取数据成功', $return_data);
                } else {
                    Db::rollback();
                    apiReturn(2, '订单生成失败');
                }
            } else {
                Db::rollback();
                apiReturn(2, '购物车商品数据异常');
            }
        } catch (\Exception $e) {
            apiReturn(2, '系统繁忙，请稍后再试' . $e);
        }
    }

    /**
     * 商品确认订单
     * */
    public function confirmOrder()
    {
        $input = Request()->param();

        $user_id = $input['user_id'];
        if (checkUserStatus($user_id) === false) apiReturn(3, '您的账号已被禁用，请联系后台工作人员');
        $goods_id = $input['goods_id'];
        $sku_id = $input['sku_id'];
        $count = $input['count'];

        if (empty($user_id)) apiReturn(3, '您还未登录，请先登录');
        if (empty($goods_id)) apiReturn(2, '商品ID缺失');
        if (empty($sku_id)) apiReturn(2, '属性ID缺失');
        if (empty($count)) apiReturn(2, '商品数量异常');

        $goods_info = Db::name('mini_goods')->where(['id' => $goods_id])->find();
        $goods_img = $goods_info['img'];

        $sku_info = Db::name('mini_sku_value')->field('sku_id,img,price,use_coupon_price,goods_id,status')->where(['sku_id' => $sku_id, 'goods_id' => $goods_id])->find();
        if ($sku_info) {
            if ($sku_info['status'] == 0) apiReturn(2, '商品该规格已禁用');

            $sku_info['goods_name'] = Db::name('mini_goods')->where(['id' => $sku_info['goods_id']])->value('name');
            $sku_info['img'] = getPicture($sku_info['img']);
            $sku_info['sku'] = implode('，', array_column(getSkuName(explode('-', $sku_info['sku_id'])), 'name'));
            $all_price = sprintf("%.2f", $sku_info['price'] * $count);
            $all_use_coupon_price = sprintf("%.2f", $sku_info['use_coupon_price'] * $count);

            //默认收货地址
            $default_address = Db::name('mini_address')->field('id,username,mobile,title,detail_address')->where(['user_id' => $user_id])->order('is_default desc,id desc')->find();
            $default_address['address'] = $default_address['title'] . $default_address['detail_address'];
            unset($default_address['title'], $default_address['detail_address']);

            // 用户抵扣券数量
            $coupon_count = Db::table('fa_user')->where(['id' => $user_id])->value('coupon_count');

            $data = [
                'goods_type' => $goods_info['one_type_id'],
                'goods_img' => getPicture($goods_img),
                'goods_info' => $sku_info,
                'all_price' => $all_price,
                'all_use_coupon_price' => $all_use_coupon_price,
                'address' => $default_address ? : [],
                'coupon_count' => $coupon_count
            ];

            apiReturn(1, '获取数据成功', $data);
        } else {
            apiReturn(2, '规格不存在或已删除');
        }
    }

    /**
     * 立即支付【生成待支付订单】 之后 发起支付
     * */
    public function addGoodsOrder()
    {
        $input = Request()->param();

        $user_id = $input['user_id'];
        if (checkUserStatus($user_id) === false) apiReturn(3, '您的账号已被禁用');
        $goods_id = $input['goods_id'];
        $count = $input['count'];
        $sku_id = $input['sku_id'];
        $pay_price = $input['pay_price'];
        $address_id = $input['address_id'];
        $use_coupon = $input['use_coupon'];
        $pay_type = $input['pay_type'];
        $remark = $input['remark'];
        $from = $input['from'] ? : 2;// H5端该参数传1，小程序默认可以不传

        if (empty($user_id)) apiReturn(3, '您还未登录，请先登录');
        if (empty($goods_id)) apiReturn(2, '商品ID缺失');
        if ($count <= 0) apiReturn(2, '商品数量异常');
        if (empty($sku_id)) apiReturn(2, '属性ID缺失');
        if ($pay_price <= 0) apiReturn(2, '商品金额错误');

        $sku_info = Db::name('mini_sku_value')->where(['sku_id' => $sku_id, 'goods_id' => $goods_id])->find();

        $user_info = Db::table('fa_user')->where(['id' => $user_id])->find();
        if (empty($user_info)) apiReturn(2, '用户信息不存在或已删除');

        if (empty($address_id)) apiReturn(2, '请选择收货地址');

        if ($pay_type == 2) {
            // 使用余额支付，判断账户余额是否充足
            $money = Db::table('fa_user')->where(['id' => $user_id])->value('money');
            if ($money < $pay_price) apiReturn(2, '账户余额不足');
        }

        $time = time();
        Db::startTrans();
        try {
            $goods_info = Db::name('mini_goods')->field('id,name,one_type_id,img')->where(['id' => $goods_id])->find();
            if ($goods_info) {
                if ($sku_info) {
                    // 商品单价
                    $goods_price = $use_coupon == 1 ? $sku_info['use_coupon_price'] : $sku_info['price'];
                    $all_price = $goods_price * $count;

                    $order_sn = createOrderSn();
                    $data = [
                        'user_id' => $user_id,
                        'order_sn' => $order_sn,
                        'pay_order_sn' => $order_sn,
                        'use_coupon_count' => $use_coupon == 1 ? $count : 0,
                        'all_price' => $all_price,
                        'pay_price' => $pay_price,
                        'pay_type' => $pay_type,
                        'up_vip' => $goods_info['one_type_id'] == 1 ? 1 : 0,// 报单区商品升级vip
                        'send_coupon_count' => $goods_info['one_type_id'] == 1 ? C('SEND_COUPON_COUNT') : 0,//报单区商品下单赠送5张券
                        'remark' => $remark,
                        'from' => $from,
                        'create_time' => $time
                    ];

                    $address_info = Db::name('mini_address')->where(['id' => $address_id])->find();
                    $data['get_username'] = $address_info['username'];
                    $data['get_mobile'] = $address_info['mobile'];
                    $data['get_sex'] = $address_info['sex'];
                    $data['get_address'] = $address_info['title'] . $address_info['detail_address'];
                    $data['get_lat'] = $address_info['lat'];
                    $data['get_lng'] = $address_info['lng'];

                    $order_id = Db::name('mini_order')->insertGetId($data);
                    $goods_order = [
                        'order_id' => $order_id,
                        'goods_id' => $goods_id,
                        'sku_id' => $sku_id,
                        'img' => $sku_info['img'] ? : $goods_info['img'],
                        'name' => $goods_info['name'],
                        'price' => $sku_info['price'],
                        'use_coupon_price' => $sku_info['use_coupon_price'],
                        'count' => $count,
                        'use_coupon' => $use_coupon,
                        'create_time' => $time
                    ];
                    Db::name('mini_vice_order')->insert($goods_order);

                    if ($pay_type == 1) {
                        // 调用微信支付
                        Loader::import('wxsdk\wxPay', EXTEND_PATH);
                        $obj = new \wxPay();
                        //调用示例（最后两个参数为可选参数）
                        $pay_price = 0.01;
                        $pay_data = $obj->jsApi($user_info['openid'], $pay_price, $order_sn, '商品支付', getHost() . '/Index/Notify/notice');

                        $return_data = [
                            'pay_data' => $pay_data,
                            'order_sn' => $order_sn
                        ];
                    } else {
                        // 使用余额支付
                        action('Index/Notify/doGoodsOrder', $order_sn);
                    }


                    Db::commit();
                    apiReturn(1, '获取数据成功', $return_data ? : []);
                } else {
                    Db::rollback();
                    apiReturn(2, '规格不存在或已删除');
                }
            } else {
                Db::rollback();
                apiReturn(2, '商品不存在或已删除');
            }
        } catch (\Exception $e) {
            Db::rollback();
            apiReturn(2, '系统繁忙，请稍后再试' . $e);
        }
    }

    /**
     * 收货地址列表
     * */
    public function addressList()
    {
        $input = Request()->param();
        $user_id = $input['user_id'];

        if (empty($user_id)) apiReturn(3, '您还未登录，请先登录');

        if (checkUserStatus($user_id) === false) apiReturn(3, '您的账号已被禁用');

        $list = Db::name('mini_address')->where(['user_id' => $user_id])->order('is_default desc,create_time desc')->select();
        if ($list) {
            apiReturn(1, '获取数据成功', $list);
        } else {
            apiReturn(2, '暂无收货地址', []);
        }
    }

    /**
     * 收货地址详情
     * */
    public function addressDetail()
    {
        $input = Request()->param();

        $id = $input['id'];

        if (empty($id)) apiReturn(2, '收货地址ID缺失');

        $info = Db::name('mini_address')->where(['id' => $id])->find();
        if ($info) {
            apiReturn(1, '获取数据成功', $info);
        } else {
            apiReturn(2, '收货地址不存在或已删除');
        }
    }

    /**
     * 添加收货地址
     * */
    public function doAddress()
    {
        $input = Request()->param();

        $id = $input['id'];
        $user_id = $input['user_id'];
        if (checkUserStatus($user_id) === false) apiReturn(3, '您的账号已被禁用，请联系后台工作人员');
        $username = $input['username'];
        $mobile = $input['mobile'];
        $sex = $input['sex'];
        $title = $input['title'];
        $address = $input['address'];
        $detail_address = $input['detail_address'];
        $lat = $input['lat'];
        $lng = $input['lng'];
        $is_default = $input['is_default'];

        if (empty($user_id)) apiReturn(3, '您还未登录，请先登录');
        if (empty($lat) || empty($lng) || empty($address) || empty($title)) apiReturn(2, '请选择位置');
        if (empty($detail_address)) apiReturn(2, '请输入门牌号');
        if (empty($username)) apiReturn(2, '请填写联系人');
        if (empty($mobile)) apiReturn(2, '请填写手机号');

        $time = time();
        $data = [
            'user_id' => $user_id,
            'username' => $username,
            'mobile' => $mobile,
            'sex' => $sex,
            'title' => $title,
            'address' => $address,
            'detail_address' => $detail_address,
            'lat' => $lat,
            'lng' => $lng,
            'is_default' => $is_default,
        ];
        if ($is_default == 1) Db::name('mini_address')->where(['user_id' => $user_id])->setField('is_default', 0);

        if ($id) {
            $data['update_time'] = $time;
            $res = Db::name('mini_address')->where(['id' => $id])->update($data);
        } else {
            $data['create_time'] = $time;
            $res = Db::name('mini_address')->insert($data);
        }

        if ($res) {
            apiReturn(1, '添加成功');
        } else {
            apiReturn(2, '添加失败');
        }
    }

    /**
     * 设置默认地址
     * */
    public function setDefaultAddress()
    {
        $input = Request()->param();

        $id = $input['id'];

        if (empty($id)) apiReturn(2, '收货地址ID缺失');

        Db::startTrans();
        try {
            $info = Db::name('mini_address')->where(['id' => $id])->find();
            if ($info) {
                Db::name('mini_address')->where(['user_id' => $info['user_id']])->setField('is_default', 0);
                Db::name('mini_address')->where(['id' => $id])->setField('is_default', 1);

                Db::commit();
                apiReturn(1, '设置成功');
            } else {
                Db::rollback();
                apiReturn(2, '收货地址不存在或已删除');
            }
        } catch (\Exception $e) {
            Db::rollback();
            apiReturn(2, '设置失败');
        }
    }

    /**
     * 删除收货地址
     * */
    public function delAddress()
    {
        $input = Request()->param();

        $id = $input['id'];

        if (empty($id)) apiReturn(2, '收货地址ID缺失');

        $info = Db::name('mini_address')->where(['id' => $id])->find();
        if ($info) {
            $res = Db::name('mini_address')->where(['id' => $id])->delete();
            if ($res) {
                apiReturn(1, '删除成功');
            } else {
                apiReturn(2, '删除失败');
            }
        } else {
            apiReturn(2, '收货地址不存在或已删除');
        }
    }

    /**
     * 个人中心
     * */
    public function userCenter()
    {
        $input = Request()->param();

        $user_id = $input['user_id'];

        if (checkUserStatus($user_id) === false) apiReturn(3, '您的账号已被禁用');
        if (empty($user_id)) apiReturn(3, '您还未登录，请先登录');

        $info = Db::table('fa_user')->field('id,user_type,avatar,nickname,mobile,money,score,coupon_count,pay_pwd,unique_id,qr,share_url')->where(['id' => $user_id])->find();
        if ($info) {
            // 生成微信小程序码
            if (!$info['qr']) createUserQr($user_id);
            if (!$info['share_url']) createMiniShareUrl($user_id);

            $hide_mobile = hideMobile($info['mobile']);
            $info['hide_mobile'] = $hide_mobile;
            $info['avatar'] = doImgPath($info['avatar']);
            $info['qr'] = doImgPath($info['qr']);

            $info['nickname'] = $info['nickname'] ? : $hide_mobile;

            $order_where = [
                'user_id' => $user_id,
                'is_del' => 0
            ];
            // 待发送订单数量
            $wait_send_order_count = Db::name('mini_order')->where($order_where)->where(['status' => 1])->count();
            // 待收货订单数量
            $wait_get_order_count = Db::name('mini_order')->where($order_where)->where(['status' => 2])->count();
            // 已完成订单数量
            $wait_complete_order_count = Db::name('mini_order')->where($order_where)->where(['status' => 5])->count();

            $info['wait_send_order_count'] = $wait_send_order_count;
            $info['wait_get_order_count'] = $wait_get_order_count;
            $info['wait_complete_order_count'] = $wait_complete_order_count;

            $info['is_set_pay_pwd'] = (bool)$info['pay_pwd'];
            unset($info['pay_pwd']);
            unset($info['mobile']);

            apiReturn(1, '获取数据成功', $info);
        } else {
            apiReturn(3, '用户不存在或已禁用');
        }
    }

    /**
     * 提现记录
     * */
    public function withdrawalList()
    {
        $input = Request()->param();

        $user_id = $input['user_id'];
        if (checkUserStatus($user_id) === false) apiReturn(3, '您的账号已被禁用，请联系后台工作人员');
        $page = $input['page'] ? : 1;
        $pagesize = $input['pagesize'] ? : 10;

        if (empty($user_id)) apiReturn(3, '您还未登录，请先登录');

        $list = Db::name('mini_withdrawal')->field('id,real_price price,type,status,create_time')->where(['user_id' => $user_id])->order('create_time desc')->page($page, $pagesize)->select();
        if ($list) {
            foreach ($list as &$v) {
                $v['desc'] = $v['status'] == 1 ? '提现到' . ($v['type'] == 1 ? '微信钱包' : '银行卡') : '提现审核失败';
                $v['change'] = $v['status'] == 1 ? 'plus' : 'minus';
                $v['create_time'] = timeFormat($v['create_time']);
            }
            apiReturn(1, '获取数据成功', $list);
        } else {
            apiReturn(2, '暂无更多数据', []);
        }
    }

    /**
     * 订单列表
     * */
    public function orderList()
    {
        $input = Request()->param();

        $user_id = $input['user_id'];
        if (checkUserStatus($user_id) === false) apiReturn(3, '您的账号已被禁用，请联系后台工作人员');
        $status = $input['status'] ? : 0;
        $from = $input['from'] ? : 2;
        $page = $input['page'] ? : 1;
        $pagesize = $input['pagesize'] ? : 10;

        if (empty($user_id)) apiReturn(3, '您还未登录，请先登录');

        $where['user_id'] = $user_id;
        $where['from'] = $from;
        $where['is_del'] = 0;
        if ($status) $where['status'] = $status;
        $list = Db::name('mini_order')->field('id,order_sn,pay_price,status')->where($where)->order('create_time desc')->page($page, $pagesize)->select();
        if ($list) {
            foreach ($list as &$v) {
                $v['status_desc'] = doOrderStatus($v['status']);

                $goods_list = Db::name('mini_vice_order')->field('id,img,name,use_coupon,use_coupon_price,price,count,sku_id,goods_id')->where(['order_id' => $v['id']])->select();
                if ($goods_list) {
                    foreach ($goods_list as &$val) {
                        $val['img'] = $val['img'] ? getPicture($val['img']) : getGoodsImg($val['goods_id']);
                        if ($sku_list = getSkuName(explode('-', $val['sku_id']))) $val['sku'] = implode('，', array_column($sku_list, 'name'));
                    }
                    $v['goods_list'] = $goods_list;
                }
            }

            apiReturn(1, '获取数据成功', $list);
        } else {
            apiReturn(2, '暂无更多数据', []);
        }
    }

    /**
     * 订单详情
     * */
    public function orderDetail()
    {
        $input = Request()->param();

        $id = $input['id'];

        if (empty($id)) apiReturn(2, '订单ID缺失');

        $info = Db::name('mini_order')->where(['id' => $id])->find();

        if ($info) {
            $info['create_time'] = timeFormat($info['create_time']);
            $info['status_desc'] = doOrderStatus($info['status']);
            $info['verify_qr'] = getPicture($info['verify_qr']);


            $goods_list = Db::name('mini_vice_order')->field('id,goods_id,img,name,price,count,sku_id')->where(['order_id' => $id])->select();
            if ($goods_list) {
                foreach ($goods_list as &$val) {
                    $val['img'] = $val['img'] ? getPicture($val['img']) : getGoodsImg($val['goods_id']);
                    if ($sku_list = getSkuName(explode('-', $val['sku_id']))) $val['sku'] = implode('，', array_column($sku_list, 'name'));
                }

                $info['goods_list'] = $goods_list;
            }

            apiReturn(1, '获取数据成功', $info);
        } else {
            apiReturn(2, '订单不存在或已删除');
        }
    }

    /**
     * 确认收货
     * */
    public function confirmGet()
    {
        $input = Request()->param();

        $id = $input['id'];

        if (empty($id)) apiReturn(2, '订单ID缺失');

        $info = Db::name('mini_order')->where(['id' => $id])->find();
        if ($info) {
            Db::startTrans();
            try {
                Db::name('mini_order')->where(['id' => $id])->update(['status' => 3, 'update_time' => time()]);

                Db::commit();
                apiReturn(1, '操作成功');
            } catch (\Exception $e) {
                Db::rollback();
                apiReturn(2, '操作失败');
            }
        } else {
            apiReturn(2, '订单不存在');
        }
    }

    /**
     * 获取评价页面订单商品信息
     * */
    public function getOrderGoodsList()
    {
        $input = Request()->param();

        $id = $input['id'];

        if (empty($id)) apiReturn(2, '订单ID缺失');

        $goods_list = Db::name('mini_vice_order')->where(['order_id' => $id])->select();
        if ($goods_list) {
            foreach ($goods_list as &$v) {
                $v['img'] = $v['img'] ? getPicture($v['img']) : getGoodsImg($v['goods_id']);
                $v['all_price'] = sprintf('%.2f', ($v['use_coupon'] == 1 ? $v['use_coupon_price'] : $v['price']) * $v['count']);

                if ($sku_list = getSkuName(explode('-', $v['sku_id']))) $v['sku'] = implode('，', array_column($sku_list, 'name'));
            }
            apiReturn(1, '获取数据成功', $goods_list);
        } else {
            apiReturn(2, '未查询到商品信息');
        }
    }

    /**
     * 商品评价
     * */
    public function goodsComment()
    {
        $input = Request()->param();

        $comment_list = json_decode($input['comment_list'], true);

        Db::startTrans();
        try {
            $time = time();
            if ($comment_list) {
                $have_empty = false;
                $data = [];
                foreach ($comment_list as &$v) {
                    if (empty($v['content'])) {
                        $have_empty = true;
                        break;
                    } else {
                        checkContent($v['content']);

                        $data[] = [
                            'user_id' => $v['user_id'],
                            'order_id' => $v['order_id'],
                            'vice_order_id' => $v['vice_order_id'],
                            'goods_id' => $v['goods_id'],
                            'star' => $v['star'],
                            'content' => $v['content'],
                            'imgs' => $v['imgs_id'],
                            'create_time' => $time
                        ];
                    }
                }

                if ($have_empty) apiReturn(2, '请针对所有商品作出评价');

                Db::name('mini_goods_comment')->insertAll($data);

                $order_id = Db::name('mini_vice_order')->where(['id' => $comment_list[0]['vice_order_id']])->value('order_id');
                $order_data = [
                    'status' => 4,
                    'update_time' => $time
                ];
                Db::name('mini_order')->where(['id' => $order_id])->update($order_data);

                Db::commit();
                apiReturn(1, '评价成功');
            } else {
                Db::rollback();
                apiReturn(2, '评价数据出错，请稍后再试~');
            }
        } catch (\Exception $e) {
            Db::rollback();
            apiReturn(2, '系统繁忙，请稍后再试~');
        }
    }

    /**
     * 删除订单
     * */
    public function delOrder()
    {
        $input = Request()->param();

        $id = $input['id'];

        if (empty($id)) apiReturn(2, '订单ID缺失');

        $info = Db::name('mini_order')->where(['id' => $id, 'is_del' => 0])->find();
        if ($info) {
            $res = Db::name('mini_order')->where(['id' => $id])->setField('is_del', 1);
            if ($res) {
                apiReturn(1, '删除成功');
            } else {
                apiReturn(2, '删除失败');
            }
        } else {
            apiReturn(2, '订单不存在或已删除');
        }
    }

    /**
     * 信息设置回显数据
     * */
    public function userInfo()
    {
        $input = Request()->param();

        $user_id = $input['user_id'];
        if (checkUserStatus($user_id) === false) apiReturn(3, '您的账号已被禁用，请联系后台工作人员');

        if (empty($user_id)) apiReturn(3, '您还未登录，请先登录');

        $user_info = Db::table('fa_user')->field('id,avatar,nickname,gender')->where(['id' => $user_id])->find();
        if ($user_info) {
            $user_info['avatar_path'] = doImgPath($user_info['avatar']);
            apiReturn(1, '获取数据成功', $user_info);
        } else {
            apiReturn(2, '用户信息不存在或已禁用');
        }
    }

    /**
     * 保存用户信息
     * */
    public function saveUserInfo()
    {
        $input = Request()->param();

        $user_id = $input['user_id'];
        $avatar = $input['avatar'];
        $nickname = $input['nickname'];
        $gender = $input['gender'];

        if (checkUserStatus($user_id) === false) apiReturn(3, '您的账号已被禁用');

        if (empty($user_id)) apiReturn(3, '您还未登录，请先登录');
        if (empty($nickname)) apiReturn(2, '请输入昵称');

        Db::startTrans();
        try {
            $info = Db::table('fa_user')->where(['id' => $user_id])->find();

            if ($info) {
                $data = [
                    'avatar' => str_replace(getHost(), '', $avatar),
                    'nickname' => $nickname,
                    'gender' => $gender,
                    'updatetime' => time()
                ];

                Db::table('fa_user')->where(['id' => $user_id])->update($data);

                Db::commit();
                apiReturn(1, '保存成功');
            } else {
                Db::rollback();
                apiReturn(3, '用户不存在');
            }
        } catch (\Exception $e) {
            Db::rollback();
            apiReturn(2, '保存失败' . $e->getMessage());
        }
    }

    /**
     * 积分明细
     * */
    public function scoreList()
    {
        $input = Request()->param();

        $user_id = $input['user_id'];
        if (checkUserStatus($user_id) === false) apiReturn(3, '您的账号已被禁用');
        $page = $input['page'] ? : 1;
        $pagesize = $input['pagesize'] ? : 10;

        $score = Db::table('fa_user')->where(['id' => $user_id])->value('score');

        $list = Db::name('mini_user_score_log')->where(['user_id' => $user_id])->order('id desc')->page($page, $pagesize)->select();
        if ($list) {
            foreach ($list as &$v) {
                $v['create_time'] = timeFormat($v['create_time'], 'Y-m-d');
            }
        }

        $data = [
            'score' => $score,
            'list' => $list ? : []
        ];
        apiReturn(1, '获取数据成功', $data);
    }

    /**
     * 抵扣券明细
     * */
    public function couponList()
    {
        $input = Request()->param();

        $user_id = $input['user_id'];
        if (checkUserStatus($user_id) === false) apiReturn(3, '您的账号已被禁用');
        $page = $input['page'] ? : 1;
        $pagesize = $input['pagesize'] ? : 10;

        $coupon_count = Db::table('fa_user')->where(['id' => $user_id])->value('coupon_count');

        $list = Db::name('mini_user_coupon_log')->where(['user_id' => $user_id])->order('id desc')->page($page, $pagesize)->select();
        if ($list) {
            foreach ($list as &$v) {
                $v['create_time'] = timeFormat($v['create_time'], 'Y-m-d');
            }
        }

        $data = [
            'coupon_count' => $coupon_count,
            'list' => $list ? : []
        ];
        apiReturn(1, '获取数据成功', $data);
    }

    /**
     * 钱包明细
     * */
    public function moneyList()
    {
        $input = Request()->param();

        $user_id = $input['user_id'];
        $is_withdrawal = $input['is_withdrawal'] ? : 0;
        $page = $input['page'] ? : 1;
        $pagesize = $input['pagesize'] ? : 10;
        $from = $input['from'] ? : 2;// H5端该参数传1，小程序默认可以不传

        if (checkUserStatus($user_id) === false) apiReturn(3, '您的账号已被禁用');

        $money = Db::table('fa_user')->where(['id' => $user_id])->value('money');

        $where = ['user_id' => $user_id, 'from' => 2];
        if ($is_withdrawal == 1) {
            $where['type'] = ['IN', [3, 4]];
            if ($from == 2) $where['from'] = $from;
        }
        $list = Db::name('mini_user_money_log')->where($where)->order('create_time desc')->page($page, $pagesize)->select();
        if ($list) {
            foreach ($list as &$v) {
                $v['change_type'] = $v['before'] < $v['after'] ? 'inc' : 'dec';
                $v['create_time'] = timeFormat($v['create_time'], 'Y-m-d');
            }
        }

        $data = [
            'money' => sprintf('%.2f', $money),
            'list' => $list ? : []
        ];
        apiReturn(1, '获取数据成功', $data);
    }

    /**
     * 申请提现
     * */
    public function applyWithdrawal()
    {
        $input = Request()->param();

        $user_id = $input['user_id'];
        $money = $input['money'];
        $username = $input['username'];
        $bank_card_num = $input['bank_card_num'];
        $bank_name = $input['bank_name'];

        if (empty($user_id)) apiReturn(3, '您还未登录，请先登录');
        if (checkUserStatus($user_id) === false) apiReturn(3, '您的账号已被禁用');
        if (empty($money)) apiReturn(2, '请输入提现金额');
        if (empty($username)) apiReturn(2, '请输入持卡人姓名');
        if (empty($bank_card_num)) apiReturn(2, '请输入银行卡号');
        if (empty($bank_name)) apiReturn(2, '请输入银行名称');
        if ($money <= 0) apiReturn(2, '提现金额必须大于0');

        $user_info = Db::table('fa_user')->where('id', $user_id)->find();
        if (empty($user_info)) apiReturn(3, '用户不存在');

        if ($user_info['money'] < $money) apiReturn(2, '您的余额不足');

        Db::startTrans();
        try {
            $time = time();

            Db::table('fa_user')->where('id', $user_id)->setDec('money', $money);

            $withdraw_data = [
                'user_id' => $user_id,
                'money' => $money,
                'pay_type' => 2,
                'bank_name' => $bank_name,
                'user_name' => $username,
                'card_num' => $bank_card_num,
                'createtime' => $time,
                'from' => 2
            ];
            $id = Db::table('fa_user_withdraw')->insertGetId($withdraw_data);

            $log_data = [
                'user_id' => $user_id,
                'money' => $money,
                'before' => $user_info['money'],
                'after' => $user_info['money'] - $money,
                'type' => 3,
                'remark' => '余额提现',
                'create_time' => $time,
                'link_id' => $id,
                'link_table' => 'fa_user_withdraw',
                'from' => 2
            ];
            Db::name('mini_user_money_log')->insert($log_data);


            Db::commit();
            apiReturn(1, '申请提现成功');
        } catch (Exception $e) {
            Db::rollback();
            apiReturn(2, '申请提现失败');
        }
    }

    /**
     * 用户抵扣券页面数据回显
     * */
    public function userCouponInfo()
    {
        $input = Request()->param();

        $user_id = $input['user_id'];
        $page = $input['page'] ? : 1;
        $pagesize = $input['pagesize'] ? : 10;

        if (empty($user_id)) apiReturn(3, '您还未登录，请先登录');

        $coupon_count = Db::table('fa_user')->where('id', $user_id)->value('coupon_count');

        $list = Db::name('mini_user_coupon_log')->where('user_id', $user_id)->where('type', 3)->where('from', 1)->order('id desc')->page($page, $pagesize)->select();
        if ($list) {
            $list = addOtherTableDataToList($list, 'link_id', Db::table('fa_user'), 'user_info', 'avatar,nickname,mobile,user_type,jointime', 'id');
            foreach ($list as &$v) {
                $v['user_info']['avatar'] = doImgPath($v['user_info']['avatar']);
                $v['user_info']['jointime'] = timeFormat($v['user_info']['jointime'], 'Y.m.d H:i:s');
                $v['user_info']['mobile'] = hideMobile($v['user_info']['mobile']);
            }
        }

        $data = [
            'coupon_count' => $coupon_count,
            'list' => $list
        ];

        apiReturn(1, '获取数据成功', $data);
    }

    /**
     * 赠送抵扣券
     * */
    public function sendCoupon()
    {
        $input = Request()->param();

        $user_id = $input['user_id'];
        $unique_id = $input['unique_id'];
        $count = $input['count'];
        $pay_pwd = $input['pay_pwd'];

        if (empty($user_id)) apiReturn(3, '您还未登录，请先登录');
        if (empty($id)) apiReturn(2, '请输入用户ID');
        if ($count <= 0) apiReturn(2, '请输入数量');
        if (empty($pay_pwd)) apiReturn(2, '请输入支付密码');

        $user_info = Db::table('fa_user')->field('coupon_count,pay_pwd,salt,son_ids')->where('id', $user_id)->find();
        if (empty($user_info)) apiReturn(2, '账号信息不存在');

        if (!in_array($id, explode(',', $user_info['son_ids']))) apiReturn(2, '该用户不是您的下级，无法赠送');

        $info = Db::table('fa_user')->field('coupon_count')->where('id', $id)->find();
        if (empty($info)) apiReturn(3, '用户不存在');

        if ($count > $user_info['coupon_count']) apiReturn(2, '抵扣券数量不足');
        if (!$user_info['pay_pwd']) apiReturn(4, '未设置初始支付密码');
        if ($user_info['pay_pwd'] != getEncryptPassword($pay_pwd, $user_info['salt'])) apiReturn(2, '支付密码错误');

        Db::startTrans();
        try {
            $time = time();
            $coupon_log = [
                // 赠送数据
                [
                    'user_id' => $user_id,
                    'coupon_count' => $count,
                    'before' => $user_info['coupon_count'],
                    'after' => $user_info['coupon_count'] - $count,
                    'type' => 3,
                    'remark' => '赠送抵扣券',
                    'create_time' => $time,
                    'link_id' => $id,
                    'link_table' => 'fa_user'
                ],
                // 获赠数据
                [
                    'user_id' => $id,
                    'coupon_count' => $count,
                    'before' => $info['coupon_count'],
                    'after' => $info['coupon_count'] + $count,
                    'type' => 4,
                    'remark' => '获赠抵扣券',
                    'create_time' => $time,
                    'link_id' => $user_id,
                    'link_table' => 'fa_user'
                ]
            ];
            Db::name('mini_user_coupon_log')->insertAll($coupon_log);

            Db::table('fa_user')->where('id', $user_id)->setDec('coupon_count', $count);
            Db::table('fa_user')->where('id', $id)->setInc('coupon_count', $count);

            Db::commit();
            apiReturn(1, '赠送成功');
        } catch (Exception $e) {
            Db::rollback();
            apiReturn(2, '赠送失败');
        }
    }

    /**
     * 我的推荐
     * */
    public function myRecommend()
    {
        $input = Request()->param();

        $user_id = $input['user_id'];
        $user_type = $input['user_type'] ? : 1;
        $page = $input['page'] ? : 1;
        $pagesize = $input['pagesize'] ? : 10;

        if (empty($user_id)) apiReturn(3, '您还未登录，请先登录');

        $no_vip_count = Db::table('fa_user')->where('parent_user_id', $user_id)->where('user_type', 1)->count();
        $vip_count = Db::table('fa_user')->where('parent_user_id', $user_id)->where('user_type', 2)->count();

        $list = Db::table('fa_user')->field('id,avatar,mobile,user_type,coupon_count,jointime')->where('parent_user_id', $user_id)->where('user_type', $user_type)->order('id desc')->page($page, $pagesize)->select();
        if ($list) {
            foreach ($list as &$v) {
                $v['avatar'] = doImgPath($v['avatar']);
                $v['mobile'] = hideMobile($v['mobile']);
                $v['jointime'] = timeFormat($v['jointime'], 'Y.m.d H:i:s');
            }
        }

        $data = [
            'no_vip_count' => $no_vip_count,
            'vip_count' => $vip_count,
            'list' => $list
        ];

        apiReturn(1, '获取数据成功', $data);
    }

    /**
     * 兑换抵扣券信息
     * */
    public function exchangeCouponInfo()
    {
        $input = Request()->param();

        $user_id = $input['user_id'];
        $page = $input['page'] ? : 1;
        $pagesize = $input['pagesize'] ? : 10;

        if (empty($user_id)) apiReturn(3, '您还未登录，请先登录');

        $score_to_coupon = C('SCORE_TO_COUPON');

        $list = Db::name('mini_user_coupon_log')->field('id,coupon_count,create_time')->where('user_id', $user_id)->where('type', 6)->where('from', 1)->order('id desc')->page($page, $pagesize)->select();
        if ($list) {
            $list = addOtherTableDataToList($list, 'id', Db::name('mini_user_score_log'), 'score', 'score', 'link_id');
            foreach ($list as &$v) {
                $v['create_time'] = timeFormat($v['create_time'], 'Y.m.d H:i:s');
            }
        }

        $data = [
            'score_to_coupon' => $score_to_coupon,
            'list' => $list
        ];

        apiReturn(1, '获取数据成功', $data);
    }

    /**
     * 兑换抵扣券
     * */
    public function exchangeCoupon()
    {
        $input = Request()->param();

        $user_id = $input['user_id'];
        $count = $input['count'];
        $use_score = $input['score'];

        if (empty($user_id)) apiReturn(3, '您还未登录，请先登录');
        if ($count <= 0) apiReturn(2, '请输入抵扣券数量');
        if ($use_score <= 0) apiReturn(2, '积分数量异常');

        $user_info = Db::table('fa_user')->where('id', $user_id)->find();
        if (empty($user_info)) apiReturn(3, '用户不存在');

        if ($user_info['score'] < $use_score) apiReturn(2, '您的积分不足');

        $time = time();

        Db::startTrans();
        try {
            $coupon_log_data = [
                'user_id' => $user_id,
                'coupon_count' => $count,
                'before' => $user_info['coupon_count'],
                'after' => $user_info['coupon_count'] + $count,
                'type' => 6,
                'create_time' => $time,
                'remark' => '积分兑换抵扣券',
                'link_table' => 'fa_mini_user_score_log'
            ];
            $coupon_log_id = Db::name('mini_user_coupon_log')->insertGetId($coupon_log_data);

            $score_log_data = [
                'user_id' => $user_id,
                'score' => $use_score,
                'before' => $user_info['score'],
                'after' => $user_info['score'] - $use_score,
                'type' => 2,
                'remark' => '兑换抵扣券',
                'create_time' => $time,
                'link_id' => $coupon_log_id,
                'link_table' => 'fa_mini_user_coupon_log'
            ];
            $score_log_id = Db::name('mini_user_score_log')->insertGetId($score_log_data);

            Db::name('mini_user_coupon_log')->where('id', $coupon_log_id)->setField('link_id', $score_log_id);

            $user_data = [
                'score' => $user_info['score'] - $use_score,
                'coupon_count' => $user_data['coupon_count'] + $count
            ];
            Db::table('fa_user')->where('id', $user_id)->update($user_data);

            Db::commit();
            apiReturn(1, '兑换成功');
        } catch (Exception $e) {
            Db::rollback();
            apiReturn(2, '兑换失败');
        }
    }

    /**
     * 签到页面信息
     * */
    public function signInfo()
    {
        $input = Request()->param();

        $user_id = $input['user_id'];

        if (empty($user_id)) apiReturn(3, '您还未登录，请先登录');


        $date = date('Y-m-d');
        $today_info = Db::name('mini_sign')->where('user_id', $user_id)->where('date', $date)->find();
        if ($today_info) {
            $days = $today_info['days'];
            $is_sign = true;
        } else {
            $prev_date = date('Y-m-d', strtotime('-1 day', strtotime($date))); // 获取前一天的日期
            $prev_info = Db::name('mini_sign')->where('user_id', $user_id)->where('date', $prev_date)->find();

            $days = $prev_info['days'];
            $is_sign = false;
        }

        $data = [
            'max_sign_day' => intval(C('MAX_SIGN_DAY')),
            'sign_rule' => C('SIGN_RULE'),
            'days' => $days ? : 0,
            'is_sign' => $is_sign
        ];

        apiReturn(1, '获取数据成功', $data);
    }

    /**
     * 签到
     * */
    public function sign()
    {
        $input = Request()->param();

        $user_id = $input['user_id'];

        if (empty($user_id)) apiReturn(3, '您还未登录，请先登录');

        $user_info = Db::table('fa_user')->where('id', $user_id)->find();
        if (empty($user_info)) apiReturn(3, '用户不存在');

        $date = date('Y-m-d');
        $prev_date = date('Y-m-d', strtotime('-1 day', strtotime($date)));

        $today_info = Db::name('mini_sign')->where('user_id', $user_id)->where('date', $date)->find();
        if ($today_info) apiReturn(2, '今日已签到');

        $prev_info = Db::name('mini_sign')->where('user_id', $user_id)->where('date', $prev_date)->find();

        Db::startTrans();
        try {
            $time = time();
            if ($prev_info['get_coupon'] == 1) {
                $days = 1;
                $get_coupon = 0;
            } else {
                $days = ($prev_info['days'] ? : 0) + 1;
                $get_coupon = $days >= C('MAX_SIGN_DAY') ? 1 : 0;
            }

            $data = [
                'user_id' => $user_id,
                'date' => $date,
                'days' => $days,
                'get_coupon' => $get_coupon,
                'create_time' => $time
            ];
            $id = Db::name('mini_sign')->insertGetId($data);

            if ($get_coupon) {
                // 获取抵扣券
                Db::table('fa_user')->where('id', $user_id)->setInc('coupon_count');

                // 生成获取抵扣券记录
                $log_data = [
                    'user_id' => $user_id,
                    'coupon_count' => 1,
                    'before' => $user_info['coupon_count'],
                    'after' => $user_info['coupon_count'] + 1,
                    'type' => 5,
                    'remark' => '签到获得抵扣券',
                    'create_time' => $time,
                    'link_id' => $id,
                    'link_table' => 'fa_mini_sign'
                ];
                Db::name('mini_user_coupon_log')->insert($log_data);
            }

            Db::commit();
            apiReturn(1, '签到成功', ['days' => $days]);
        } catch (Exception $e) {
            Db::rollback();
            apiReturn(2, '签到失败');
        }
    }

    /**
     * 关于我们
     * */
    public
    function aboutUs()
    {
        $content = Db::name('mini_about_us')->where(['id' => 1])->value('content');

        $content = doEditorContent($content);

        apiReturn(1, '获取数据成功', $content);
    }

}
